package com.yeung.exception;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class MyExceptionHandler {
    //返回json数据
/*    @ResponseBody
    @ExceptionHandler(UserNotException.class)
    public Map<String, Object> handlerException1(Exception e) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", "user.notexit");
        map.put("message", e.getMessage());
        return map;
    }*/

    //自适应返回异常数据的方式
    @ExceptionHandler(UserNotException.class)
    public String handleException2(Exception e) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", "user.notexit");
        map.put("message", e.getMessage());
        //要传入状态码, 否则返回的页面是200 请求成功
        map.put("javax.servlet.error.status_code", 400);
        //转发到错误异常处理
        return "forward:/error";
    }

}
